package www.sofn.com.security.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import www.sofn.com.constant.AuthConstant;
import www.sofn.com.security.config.properties.TokenProperties;
import www.sofn.com.security.domain.vo.TokenInfoVO;
import www.sofn.com.utils.AddressUtils;
import www.sofn.com.utils.IpUtils;
import www.sofn.com.utils.ServletUtils;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenService {
    @Resource
    private TokenProperties tokenProperties;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public TokenInfoVO getTokenInfo(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotBlank(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(AuthConstant.TOKEN_ONLY_IDENTIFICATION);
            String tokenKey = getTokenKey(uuid);
            String personalInfoJsonStr = (String) redisTemplate.opsForValue().get(tokenKey);
            if(StrUtil.isBlank(personalInfoJsonStr)) return null;
            final TokenInfoVO tokenInfoVO = JSONUtil.toBean(personalInfoJsonStr, TokenInfoVO.class);
            return tokenInfoVO;
        }
        return null;
    }

     /**
      * 验证令牌有效期，相差不足20分钟，自动刷新缓存
      * verifyToken
      *@return 令牌
      */

    public void verifyToken(TokenInfoVO tokenInfoVO) {
        Long expireTime = tokenInfoVO.getExpireTime();
        Long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(tokenInfoVO);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param tokenInfoVO 登录信息
     */
    public void refreshToken(TokenInfoVO tokenInfoVO) {
        tokenInfoVO.setLoginTime(System.currentTimeMillis());
        tokenInfoVO.setExpireTime(
                Duration.ofMillis(tokenInfoVO.getLoginTime())
                        .plus(tokenProperties.getExpireTime()).toMillis()
        );
        // 根据uuid将loginUser缓存
        String tokenKey = getTokenKey(tokenInfoVO.getTokenId());
        redisTemplate.opsForValue().set(tokenKey, JSONUtil.toJsonStr(tokenInfoVO), tokenProperties.getExpireTime().toMinutes(), TimeUnit.MINUTES);
    }

    /**
     * 初始化token信息
     * @return
     */
    private TokenInfoVO initTokenInfoVO(TokenInfoVO tokenInfoVO) {
        final UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        tokenInfoVO.setIpaddr(ip);
        tokenInfoVO.setTokenId(IdUtil.fastSimpleUUID());
        tokenInfoVO.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        tokenInfoVO.setBrowser(userAgent.getBrowser().getName());
        tokenInfoVO.setOs(userAgent.getOs().getName());
       return tokenInfoVO;
    }

    /**
     * 创建令牌
     *
     * @return 令牌
     */
    public String createToken(TokenInfoVO tokenInfoVO)
    {
        initTokenInfoVO(tokenInfoVO);
        refreshToken(tokenInfoVO);
        return createToken(BeanUtil.beanToMap(tokenInfoVO));
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, tokenProperties.getSecret()).compact();
        return token;
    }


    public void delToken() {
        final TokenInfoVO tokenInfo = getTokenInfo(ServletUtils.getRequest());
        final String tokenKey = getTokenKey(tokenInfo.getTokenId());
        redisTemplate.delete(tokenKey);
    }

    /**
     * 删除token
     *
     * @param tokeId
     */
    public void delToken(String tokeId) {
        final String tokenKey = getTokenKey(tokeId);
        redisTemplate.delete(tokenKey);
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
          return   Jwts.parser()
                    .setSigningKey(tokenProperties.getSecret())
                    .parseClaimsJws(token)
                    .getBody();
    }


    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(AuthConstant.REQUEST_HEADER);
        if (StrUtil.isNotBlank(token) && token.startsWith(AuthConstant.REQUEST_HEADER_PREFIX)) {
            token = token.replace(AuthConstant.REQUEST_HEADER_PREFIX, "").trim();
        }
        return token;
    }

    private String getTokenKey(String tokenId) {
        return AuthConstant.LOGIN_ONLY_IDENTIFICATION_PREFIX + tokenId;
    }

}
